<template>
  <Dialog v-model="visible" :title="title">
    <el-form ref="formRef" v-loading="loading" :model="form" :rules="formRules">
      <el-form-item label="上级菜单">
        <el-tree-select
          v-model="form.parentId"
          :data="menuTree"
          :default-expanded-keys="[0]"
          :props="{
            children: 'children',
            label: 'label',
            value: 'pid'
          }"
          check-strictly
          node-key="pid"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="name">
        <el-input v-model="form.name" clearable placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio-button v-for="dict in dictOptions" :key="dict.label" :label="dict.value">
            {{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.type !== '3'" label="菜单图标">
        <IconSelect v-model="form.icon" clearable />
      </el-form-item>
      <el-form-item v-if="form.type !== '3'" label="路由地址" prop="path">
        <template #label>
          <Tooltip
            message="访问的路由地址,如：`user`。如需外网地址时,则以 `http(s)://` 开头"
            titel="路由地址"
          />
        </template>
        <el-input v-model="form.path" clearable placeholder="请输入路由地址" />
      </el-form-item>
      <el-form-item v-if="form.type === '2'" label="组件地址" prop="component">
        <el-input v-model="form.component" clearable placeholder="例如说：system/user/index" />
      </el-form-item>
      <el-form-item v-if="form.type === '2'" label="组件名字" prop="componentName">
        <el-input v-model="form.componentName" clearable placeholder="例如说：SystemUser" />
      </el-form-item>
      <el-form-item v-if="form.type !== '1'" label="权限标识" prop="permission">
        <template #label>
          <Tooltip
            message="Controller 方法上的权限字符,如：@PreAuthorize(`@ss.hasPermission('system:user:list')`)"
            titel="权限标识"
          />
        </template>
        <el-input v-model="form.permission" clearable placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item v-if="form.type !== '3'" label="显示状态" prop="visible">
        <template #label>
          <Tooltip message="选择隐藏时,路由将不会出现在侧边栏,但仍然可以访问" titel="显示状态" />
        </template>
        <el-radio-group v-model="form.visible">
          <el-radio key="true" :label="true" border>显示</el-radio>
          <el-radio key="false" :label="false" border>隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.type !== '3'" label="总是显示" prop="alwaysShow">
        <template #label>
          <Tooltip
            message="选择不是时,当该菜单只有一个子菜单时,不展示自己,直接展示子菜单"
            titel="总是显示"
          />
        </template>
        <el-radio-group v-model="form.alwaysShow">
          <el-radio key="true" :label="true" border>总是</el-radio>
          <el-radio key="false" :label="false" border>不是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.type === '2'" label="缓存状态" prop="keepAlive">
        <template #label>
          <Tooltip
            message="选择缓存时,则会被 `keep-alive` 缓存,必须填写「组件名称」字段"
            titel="缓存状态"
          />
        </template>
        <el-radio-group v-model="form.keepAlive">
          <el-radio key="true" :label="true" border>缓存</el-radio>
          <el-radio key="false" :label="false" border>不缓存</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="loading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemMenuForm" setup>
import * as Api from '@/api/userCenter/auth/menu'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { defaultProps, eachTree } from '@/utils/tree'

const { wsCache } = useCache()
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref(`编辑信息`) // 弹窗的标题
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const form = ref({
  id: '0',
  pid: '',
  name: '',
  permission: '',
  type: '',
  orderNum: Number(undefined),
  parentId: '0',
  path: '',
  icon: '',
  component: '',
  componentName: '',
  visible: true,
  keepAlive: true,
  alwaysShow: true
})
const formRules = reactive({
  name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const dictOptions = ref([
  { label: '目录', value: '1' },
  { label: '菜单', value: '2' },
  { label: '按钮', value: '3' }
])

/** 打开弹窗 */
const open = async (id?: string, level?: number, parentId?: string) => {
  visible.value = true

  resetForm()
  if (parentId) {
    form.value.parentId = parentId
  }
  // 修改时,设置数据
  if (id && level) {
    loading.value = true

    form.value.id = id
    try {
      let getById: any = await Api.getById(id, level)
      if (getById) {
        form.value = getById
        if (!getById.alwaysShow) {
          form.value.alwaysShow = true
        } else {
          form.value.alwaysShow = false
        }
        if (!getById.keepAlive) {
          form.value.keepAlive = true
        } else {
          form.value.keepAlive = false
        }
        if (!getById.visible) {
          form.value.visible = true
        } else {
          form.value.visible = false
        }
      }
    } catch (t) {
      console.log(t)
    } finally {
      loading.value = false
    }
  }
  // 获得菜单列表
  await getTree()
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  loading.value = true
  try {
    const data = form.value as unknown as Api.Model
    await Api.update(data)
    message.success(`操作成功`)
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (t) {
    console.log(t)
  } finally {
    loading.value = false
    // 清空,从而触发刷新
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
  }
}

/** 获取下拉框[上级菜单]的数据  */
const menuTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  menuTree.value = []
  const res = await Api.getList(null)

  let menu: Tree = { _id: 'a0', pid: 'a0', name: '系统菜单', label: '系统菜单', children: [] }

  menu.children = res

  const node = [menu]

  eachTree(node, function (element, parentNode) {
    element.label = element.name
    return element
  })

  console.log(node[0])

  menuTree.value.push(node[0])
}

/** 重 置表单 */
const resetForm = () => {
  form.value = {
    id: '',
    pid: '',
    name: '',
    permission: '',
    type: '',
    orderNum: Number(undefined),
    parentId: '',
    path: '',
    icon: '',
    component: '',
    componentName: '',
    visible: true,
    keepAlive: true,
    alwaysShow: true
  }
  formRef.value?.resetFields()
}

/** 判断 path 是不是外部的 HTTP 等链接 */
const isExternal = (path: string) => {
  return /^(https?:|mailto:|tel:)/.test(path)
}
</script>
